<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
       {
               return array(
                       array('allow',  // allow all users to perform 'index' and 'view' actions
                               'actions'=>array('index','view','create','update','admin','delete','loadimage','updatePassword'),
                               'roles'=>array('admin'),
                       ),
                       array('allow',  // allow all users to perform 'index' and 'view' actions
                               'actions'=>array('view','update','updatePassword'),
                               'roles'=>array('alumni','volunteer','encoder'),
                       ),

                       array('deny',  // deny all users
                               'users'=>array('*'),
                       ),
               );
       }

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
    {
               $user= $this->loadModel($id);

               $alumni = Alumni::model()->findByAttributes(array('user_id'=>$user->id));

               $volunteer = Volunteer::model()->findByAttributes(array('user_id'=>$user->id));

              /* $assignment = MissionAssignment::model()->findByAttributes(array('volunteer_id'=>$volunteer->user_id));*/

               $this->render('view',array(
                       'model'=>$user,
                      /* 'assignment'=>$assignment,*/
                       'volunteer'=>$volunteer,
                       'alumni'=>$alumni,
               ));
       }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
         {
           $model=new User;
  			   $user=new User();
                 // Uncomment the following line if AJAX validation is needed
                 // $this->performAjaxValidation($model);

            if(isset($_POST['User'])){
                         //for email 
  					$model->attributes=$_POST['User'];  
  					$user->attributes=$_POST['User'];
  					   
  					$firstname = $user->user_fname;
  					$lastname = $user->user_lname;
  					$pass = $user->password;
  			     
            /*--for upload image--*/
            $uploadedFile = CUploadedFile::getInstance($model, 'user_photo');
            $rnd = rand(0123456789, 9876543210); 
                         
  					  /*--password hashing--*/
  					  if($user->validate()){
                  /*$fileName = "{$rnd}-{$uploadedFile}";
                  $model->user_photo = $fileName;*/
                  
                  $salt = openssl_random_pseudo_bytes(22);
                  $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
                  $password_hash = crypt($model->password, $salt);
                  $model->password = $password_hash;
  					   }
                         
              if($model->save()){
                    if (!empty($uploadedFile)){
                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/images/'.$fileName); 
                      } // save images in given destination folder
                         
      				//use 'contact' view from views/mail
      				$mail = new YiiMailer('contact', array('Firstname' => $firstname,'Lastname' => $lastname,'Password' => $pass, 'Username' => $user->username,));
      				
      				//set properties
      				$mail->setFrom(Yii::app()->params['adminEmail']);
      				$mail->setSubject('No Reply');
      				$mail->setTo($user->user_email);
      				//send
      				if ($mail->send()) {
      					Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
      				} else {
      					Yii::app()->user->setFlash('error','Error while sending email: '.$mail->getError());
      				}
      				
                                     $this->redirect(array('view','id'=>$model->id));
                     }
             }
                     $this->render('create',array(
                             'model'=>$model,
                     ));
             }


	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
       {
               $model=$this->loadModel($id);
			         $user=$this->loadUser($model->id);
			   
               // Uncomment the following line if AJAX validation is needed
               // $this->performAjaxValidation($model);

               if(isset($_POST['User']))
               {
                       $model->attributes=$_POST['User'];
					             $user->attributes=$_POST['User'];

                       $uploadedFile = CUploadedFile::getInstance($model, 'user_photo');
                       $rnd = rand(0123456789, 9876543210); 
						
					             $fileName = "{$rnd}-{$uploadedFile}";
					             $user->user_photo = $fileName;
						
						
						/*--password hashing--*/
					  if($user->validate()){
                       $salt = openssl_random_pseudo_bytes(22);
                       $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
                       $password_hash = crypt($model->password, $salt);
                       $model->password = $password_hash;
					   }
					   
                       $fileName = "{$rnd}-{$uploadedFile}";
                       
                       if (!empty($uploadedFile)) $model->user_photo = $fileName;
       
                       if($model->save()){
                               if (!empty($uploadedFile))
                               {
                        $uploadedFile->saveAs(Yii::app()->basePath.'/../files/images/'.$fileName); // save images in given destination folder
                       }
                               $this->redirect(array('view','id'=>$model->id));
               }
       }
               $this->render('update',array(
                       'model'=>$model,
               ));
       }
	   
	   public function actionUpdatePassword($id){
				$model=$this->loadModel($id);
				$user=$this->loadUser($model->id);
				//echo $user->password;	
                if(isset($_POST['currentPass']) && isset($_POST['newPass']) && isset($_POST['repNewPass'])){
                        $user = User::model()->findByPk(Yii::app()->user->id);
                        $salt = openssl_random_pseudo_bytes(22);
                        $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
                        $password_hash = crypt($_POST['currentPass'], $salt);
                        if($password_hash === $user->password){
                                if($_POST['newPass'] == $_POST['repNewPass']){
                                $user->password =crypt($_POST['newPass'], $salt);
								$user->save();
                                $this->redirect(array('view','id'=>$model->id));
                        }
                } 
				}
				$this->render('updatePassword',array(
						'model'=>$model,));
			}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('User');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
      {
        //$model=new Member('search');
        //$model->unsetAttributes();  
        $criteria=new CDbCriteria();
        $criteria->condition = 'assignment_status=:postID';
        
        $criteria->params = array(':postID'=>'ongoing');
        $criteria->join = "JOIN volunteer v ON t.volunteer_id=v.id
                          JOIN user u ON u.id=v.user_id";
        $missionAssignment=new CActiveDataProvider('MissionAssignment',array(
                'pagination' => array(
                     'pageSize' => 30,
                ),
                'criteria'=>$criteria,
            ));  
         $model = new CActiveDataProvider('User',array(
                'pagination' => array(
                     'pageSize' => 30,
                ),
            ));  
        if (isset($_GET['keyword']) && $_GET['keyword'] != ""){
            $keyword = trim($_GET['keyword']);
            $keyword = str_replace( ' ', '', $keyword);
            
            $criteria=new CDbCriteria();
            $criteria->condition="concat_ws('',user_fname,user_lname, username) LIKE concat('%',:a,'%') OR concat_ws('',user_lname,user_fname, username) LIKE concat('%',:a,'%') OR concat_ws('',user_fname,user_lname, username) LIKE concat('%',:a,'%') OR   user_fname LIKE concat('%',:a,'%') OR user_lname LIKE concat('%',:a,'%') OR username LIKE concat('%',:a,'%')" ;
            $criteria->params = array(':a' => $keyword); 
            
            $model = new CActiveDataProvider('User',array(
                'pagination' => array(
                     'pageSize' => 30,
                ),
                'criteria'=>$criteria,
            ));  
        }


        $this->render('admin',array(
          'model'=>$model,
          'missionAssignment'=>$missionAssignment,
        ));
      }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return User the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=User::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	public function loadUser($id)
    {
     $user=User::model()->findByPk($id);
       if($user===null)
        	throw new CHttpException(404,'The requested page does not exist.');
       return $user;
    }

	/**
	 * Performs the AJAX validation.
	 * @param User $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
